# Clean Environment -----------------------------------------------------
rm(list = ls())

# Load necessary data
df_cjoint <- read_rds("df_full_cjoint.rds")
covariates <- read_rds("df_full_uod.rds")
imce <- read_rds("IMCEs.rds")
source("figure_design.R")

# Merge imce and covariates
df_imce_full <- imce %>% 
  left_join(covariates, by = "ResponseId")

# TABLE 3 -----------------------------------------------------------------

# Function to compute percentage of variation explained by party preference
compute_percentage_variation <- function(response_variable) {
  anova_model <- aov(as.formula(paste(response_variable, "~ party_preference")), data = df_imce_full)
  anova_summary <- summary(anova_model)
  ssr <- anova_summary[[1]]["party_preference", "Sum Sq"]
  sst <- sum(anova_summary[[1]][, "Sum Sq"])
  r_squared <- ssr / sst
  percentage_variation <- r_squared * 100
  round(percentage_variation, 2)
}

# Compute percentages for different variables

tab_3 <- data.frame(understanding = c("Liberal","Majoritarian","Authoritarian"),
                    percentage_partisan = c(compute_percentage_variation("lib"),compute_percentage_variation("maj"),compute_percentage_variation("auth")))

write.csv(tab_3, file = "tab_3.csv")

# FIGURE 1 ----------------------------------------------------------------

# Liberal
df_liberal <- df_cjoint %>%
  filter(cand_majoritarian == "majoritarian" | cand_authoritarian == "authoritarian" | cand_liberal == "liberal") %>%
  dplyr::select(ResponseId, choice, chosen, lib, cand_liberal) %>%
  group_by(ResponseId, choice) %>%
  mutate(cont = 1:n()) %>%
  gather("chosen", "cand_liberal", key = variable, value = number) %>%
  unite(combi, variable, cont) %>%
  spread(combi, number) %>%
  filter(cand_liberal_1 == "liberal" & cand_liberal_2 == "non-liberal" | cand_liberal_2 == "liberal" & cand_liberal_1 == "non-liberal") %>%
  mutate(chosen = case_when(
    cand_liberal_1 == "liberal" & chosen_1 == 1 ~ "liberal candidate",
    cand_liberal_2 == "liberal" & chosen_2 == 1 ~ "liberal candidate",
    TRUE ~ "non-liberal candidate"
  )) %>%
  dplyr::select(lib, chosen) %>%
  mutate(lib_rounded = round(lib * 2) / 2,
         lib_chosen = case_when(chosen == "liberal candidate" ~ 1,
                                chosen == "non-liberal candidate" ~ 0))

plot_liberal <- ggplot(df_liberal, aes(x = lib, y = lib_chosen * 100)) +
  geom_point(color = "white") +
  geom_hline(yintercept = 50, linetype = "dashed", color = "grey") +
  geom_smooth(method = "gam", formula = y ~ s(x), color = "#1f77b4") +
  labs(y = "Votes cast for liberal candidate (%)",
       x = "Liberal understanding") +
  scale_y_continuous(breaks = c(30, 50, 70, 90)) +
  coord_cartesian(ylim = c(20, 90))

plot_liberal_hist <- ggMarginal(plot_liberal, type = "histogram", margins = "x")
plot_liberal_hist
dev.copy(pdf, "fig_1a.pdf", width = 3, height = 4)
dev.off()

# Majoritarian
df_majoritarian <- df_cjoint %>%
  filter(cand_majoritarian == "majoritarian" | cand_authoritarian == "authoritarian" | cand_liberal == "liberal") %>%
  dplyr::select(ResponseId, choice, chosen, maj, cand_majoritarian) %>%
  group_by(ResponseId, choice) %>%
  mutate(cont = 1:n()) %>%
  gather("chosen", "cand_majoritarian", key = variable, value = number) %>%
  unite(combi, variable, cont) %>%
  spread(combi, number) %>%
  filter(cand_majoritarian_1 == "majoritarian" & cand_majoritarian_2 == "non-majoritarian" | cand_majoritarian_2 == "majoritarian" & cand_majoritarian_1 == "non-majoritarian") %>%
  mutate(chosen = case_when(
    cand_majoritarian_1 == "majoritarian" & chosen_1 == 1 ~ "majoritarian candidate",
    cand_majoritarian_2 == "majoritarian" & chosen_2 == 1 ~ "majoritarian candidate",
    TRUE ~ "non-majoritarian candidate"
  )) %>%
  dplyr::select(maj, chosen) %>%
  mutate(maj_rounded = round(maj * 2) / 2,
         maj_chosen = case_when(chosen == "majoritarian candidate" ~ 1,
                                chosen == "non-majoritarian candidate" ~ 0))

plot_majoritarian <- ggplot(df_majoritarian, aes(x = maj, y = maj_chosen * 100)) +
  geom_point(color = "white") +
  geom_hline(yintercept = 50, linetype = "dashed", color = "grey") +
  geom_smooth(method = "gam", formula = y ~ s(x), color = "#1f77b4") +
  labs(y = "Votes cast for majoritarian candidate (%)",
       x = "Majoritarian understanding") +
  scale_y_continuous(breaks = c(30, 50, 70, 90)) +
  coord_cartesian(ylim = c(20, 90))

plot_majoritarian_hist <- ggMarginal(plot_majoritarian, type = "histogram", margins = "x")
plot_majoritarian_hist
dev.copy(pdf, "fig_1b.pdf", width = 3, height = 4)
dev.off()

# Authoritarian
df_authoritarian <- df_cjoint %>%
  filter(cand_majoritarian == "majoritarian" | cand_authoritarian == "authoritarian" | cand_liberal == "liberal") %>%
  dplyr::select(ResponseId, choice, chosen, auth, cand_authoritarian) %>%
  group_by(ResponseId, choice) %>%
  mutate(cont = 1:n()) %>%
  gather("chosen", "cand_authoritarian", key = variable, value = number) %>%
  unite(combi, variable, cont) %>%
  spread(combi, number) %>%
  filter(cand_authoritarian_1 == "authoritarian" & cand_authoritarian_2 == "non-authoritarian" | cand_authoritarian_2 == "authoritarian" & cand_authoritarian_1 == "non-authoritarian") %>%
  mutate(chosen = case_when(
    cand_authoritarian_1 == "authoritarian" & chosen_1 == 1 ~ "authoritarian candidate",
    cand_authoritarian_2 == "authoritarian" & chosen_2 == 1 ~ "authoritarian candidate",
    TRUE ~ "non-authoritarian candidate"
  )) %>%
  dplyr::select(auth, chosen) %>%
  mutate(auth_rounded = round(auth * 2) / 2,
         auth_chosen = case_when(chosen == "authoritarian candidate" ~ 1,
                                 chosen == "non-authoritarian candidate" ~ 0))

plot_authoritarian <- ggplot(df_authoritarian, aes(x = auth, y = auth_chosen * 100)) +
  geom_point(color = "white") +
  geom_hline(yintercept = 50, linetype = "dashed", color = "grey") +
  geom_smooth(method = "gam", formula = y ~ s(x), color = "#1f77b4") +
  labs(y = "Votes cast for authoritarian candidate (%)",
       x = "Authoritarian understanding") +
  scale_y_continuous(breaks = c(30, 50, 70, 90)) +
  coord_cartesian(ylim = c(20, 90))

plot_authoritarian_hist <- ggMarginal(plot_authoritarian, type = "histogram", margins = "x")
plot_authoritarian_hist
dev.copy(pdf, "fig_1c.pdf", width = 3, height = 4)
dev.off()

# TABLE 4 -----------------------------------------------------------------

# Fit models
m1 <- lm_robust(judges_M_naive ~ lib + maj + auth + party_preference + income + education + financial_situation + gender + age, data = df_imce_full)
m2 <- lm_robust(judges_A_naive ~ lib + maj + auth + party_preference + income + education + financial_situation + gender + age, data = df_imce_full)
m3 <- lm_robust(media_M_naive ~ lib + maj + auth + party_preference + income + education + financial_situation + gender + age, data = df_imce_full)
m4 <- lm_robust(media_A_naive ~ lib + maj + auth + party_preference + income + education + financial_situation + gender + age, data = df_imce_full)

# Output regression results
texreg(list(m1, m2, m3, m4),
       include.ci = FALSE,
       digits = 3,
       booktabs = TRUE,
       file = "tab_4.tex",
       include.rmse = FALSE,
       custom.coef.map = list(
         "lib" = "Liberal understanding",
         "maj" = "Majoritarian understanding",
         "auth" = "Authoritarian understanding",
         "party_preferenceLaw and Justice (PiS)" = "Law and Justice",
         "party_preferenceCivic Coalition" = "Civic Coalition",
         "party_preferencePoland 2050" = "Poland 2050",
         "party_preferenceThe Left" = "The Left",
         "party_preferenceConfederation" = "Confederation",
         "party_preferenceDon't know/none"  = "Don't know/none",
         "(Intercept)" = "Constant"
       ),
       omit.coef = c("income", "education", "financial_situation", "gender", "age"),
       custom.header = list("Judges" = 1:2, "Media" = 3:4),
       custom.model.names = c("Majoritarian", "Authoritarian", "Majoritarian", "Authoritarian"),
       groups = list("Party preference (baseline = PiS)" = 4:8),
       custom.gof.rows = list("Socioeconomic controls" = c("$\\checkmark$", "$\\checkmark$", "$\\checkmark$", "$\\checkmark$"))
       )

summary(m1)

# TABLE 5 -----------------------------------------------------------------

df_cjoint %>%
  mutate(
    undemocratic = case_when(
      attr_judges == "judges_L" & attr_media == "media_L" ~ 0,
      TRUE ~ 1
    ),
    co_partisan = case_when(
      (attr_party == "Law and Justice (PiS)" & party_preference == "Law and Justice (PiS)") |
        (attr_party == "Civic Coalition" & party_preference == "Civic Coalition") |
        (attr_party == "Poland 2050" & party_preference == "Poland 2050") |
        (attr_party == "Confederation" & party_preference == "Confederation") |
        (attr_party == "The Left" & party_preference == "The Left") ~ 1,
      TRUE ~ 0
    ),
    party_PiS = case_when(attr_party == "Law and Justice (PiS)" ~ 1, TRUE ~ 0),
    party_KO = case_when(attr_party == "Civic Coalition" ~ 1, TRUE ~ 0),
    party_Polska = case_when(attr_party == "Poland 2050" ~ 1, TRUE ~ 0),
    party_Konf = case_when(attr_party == "Confederation" ~ 1, TRUE ~ 0),
    party_Lewica = case_when(attr_party == "The Left" ~ 1, TRUE ~ 0),
    co_partisan_undemocratic = case_when(
      co_partisan == 1 & undemocratic == 1 ~ 1,
      TRUE ~ 0
    ),
    chosen_undemocratic_co_partisan = case_when(
      co_partisan_undemocratic == 1 & chosen == 1 ~ 1,
      TRUE ~ 0
    ),
    party_preference = factor(party_preference, levels = c(
      "Civic Coalition", "Confederation", "Law and Justice (PiS)", 
      "Poland 2050", "The Left"))
  ) -> df_cjoint_recoded

df_cjoint_recoded %>%
  group_by(ResponseId, choice) %>%
  summarise(
    n_undemocratic = sum(undemocratic),
    n_PiS = sum(party_PiS),
    n_KO = sum(party_KO),
    n_Polska = sum(party_Polska),
    n_Konf = sum(party_Konf),
    n_Lewica = sum(party_Lewica)
  ) %>%
  ungroup() %>%
  mutate(
    one_undemocratic = case_when(n_undemocratic == 1 ~ 1, TRUE ~ 0),
    cross_party = case_when(
      n_PiS == 2 | n_KO == 2 | n_Polska == 2 | n_Konf == 2 | n_Lewica == 2 ~ 0,
      TRUE ~ 1
    )
  ) -> pair_coding

df_cjoint_recoded %>%
  left_join(pair_coding, by = c("ResponseId", "choice")) ->
  df_cjoint_recoded_2

df_cjoint_recoded_2 %>%
  filter(
    cross_party == 1,
    one_undemocratic == 1,
    co_partisan_undemocratic == 1
  ) %>%
  mutate(party_preference = factor(party_preference, levels = c(
    "Civic Coalition", "Confederation", "Law and Justice (PiS)",
    "Poland 2050", "The Left"))
  ) -> subset

m1 <- lm_robust(chosen_undemocratic_co_partisan ~ lib + party_preference + income + education + financial_situation + gender + age,
                clusters = ResponseId, data = subset)

m2 <- lm_robust(chosen_undemocratic_co_partisan ~ maj + party_preference + income + education + financial_situation + gender + age,
                clusters = ResponseId, data = subset)

m3 <- lm_robust(chosen_undemocratic_co_partisan ~ auth + party_preference + income + education + financial_situation + gender + age,
                clusters = ResponseId, data = subset)

m4 <- lm_robust(chosen_undemocratic_co_partisan ~ lib + maj + auth + party_preference + income + education + financial_situation + gender + age,
                clusters = ResponseId, data = subset)

texreg(list(m1, m2, m3, m4),
       include.ci = FALSE,
       digits = 3,
       booktabs = TRUE,
       file = "tab_5.tex",
       include.rmse = FALSE,
       omit.coef = c("income", "education", "financial_situation", "gender", "age"),
       custom.coef.map = list(
         "lib" = "Liberal understanding",
         "maj" = "Majoritarian understanding",
         "auth" = "Authoritarian understanding",
         "party_preferenceLaw and Justice (PiS)" = "Law and Justice",
         "party_preferencePoland 2050" = "Poland 2050",
         "party_preferenceThe Left" = "The Left",
         "party_preferenceConfederation" = "Confederation",
         "(Intercept)" = "Constant"
       ),
       custom.gof.rows = list("Socioeconomic controls" = c("$\\checkmark$", "$\\checkmark$", "$\\checkmark$", "$\\checkmark$")),
       custom.gof.names = c(NA, NA, "$N$ Choices", "$N$ Respondents"))